package com.ling.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ling.bean.*;
import com.ling.dto.RecommendationDto;
import com.ling.service.BlogService;
import com.ling.service.BlogTypeService;
import com.ling.service.UserAreaService;
import com.ling.service.UserService;
import com.ling.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
public class UserBlogController {
    private final BlogService blogService;
    private final BlogTypeService blogTypeService;
    private final UserService userService;
    private final UserAreaService userAreaService;

    @Autowired
    public UserBlogController(BlogService blogService, BlogTypeService blogTypeService, UserService userService, UserAreaService userAreaService) {
        this.blogService = blogService;
        this.blogTypeService = blogTypeService;
        this.userService = userService;
        this.userAreaService = userAreaService;
    }

    @RequestMapping(value = "/blog-all", method = RequestMethod.GET)
    public String goToHomePage() {
        return "blog-all";
    }

    //跳转到写文章页面，默认使用常规编辑器
    @RequestMapping(value = "/blog-write", method = RequestMethod.GET)
    public String goToBlogWriteGeneral() {
        return "blog-write";
    }

    //发布博客
    @RequestMapping(value = "/postBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg submitBlog(Blog blog,HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        if (user == null) {
            return Msg.fail().add("error", "请重新登陆");
        }
        blog.setId(StringUtil.getRandomString(16));
        blog.setEdittime(new Date());
        blog.setUpvotenum(0);
        blog.setDownvotenum(0);
        //默认不置顶
        blog.setBlogstatus(1);
        blog.setTop(0);
        blog.setReadcount(0);
        //保存
        blogService.saveBlog(blog);

        //插入到elasticsearch数据库中
        RecommendationDto recommendationDto = new RecommendationDto();
        recommendationDto.setId(blog.getId());
        recommendationDto.setType(1);
        recommendationDto.setTitle(blog.getBlogtitle());
        recommendationDto.setContent(blog.getBlogcontent().replaceAll("<[.[^<]]*>", ""));

        String url = "http://localhost:9200/blog/blog/" + blog.getId();
        System.out.println("正在存放博客"+blog.getId());
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.put(url,recommendationDto);

        //修改博客类别相应的文章数
        UserBlogType userBlogType = blogTypeService.getUserBlogTypeById(blog.getBlogtypeid());
        userBlogType.setBlognum(userBlogType.getBlognum() + 1);
        blogTypeService.updateBlogType(userBlogType);
        //经验值+5
        User userById = userService.getUserById(user.getId());
        userById.setJiyan(userById.getJiyan()+5);
        userService.updateUserProfile(userById);
        httpSession.setAttribute("user",userById);
        //相应领域能力+5
        UserArea userArea = userAreaService.getUserArea(user.getId(), blog.getAreaid());
        if (userArea != null) {
            userArea.setAbility(userArea.getAbility() + 5);
            userAreaService.updateAbility(userArea);
        }else{
            UserArea userArea1 = new UserArea();
            userArea1.setId(StringUtil.getRandomString(16));
            userArea1.setAbility(0);
            userArea1.setAreaid(blog.getAreaid());
            userArea1.setUserid(user.getId());
            userAreaService.saveUserArea(userArea1);
        }
        return Msg.success().add("blogId", blog.getId());
    }

    //删除博客，不直接删除，只是将博客类型修改为2
    @RequestMapping(value = "/recycleBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg recycleBlog(@RequestParam String id) {
        Blog blog = new Blog();
        blog.setId(id);
        //设置为回收状态
        blog.setBlogstatus(2);
        blogService.updateBlog(blog);
        return Msg.success();
    }

    //还原博客
    @RequestMapping(value = "/repostBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg repostBlog(@RequestParam String id) {
        Blog blog = new Blog();
        blog.setId(id);
        //重新发布
        blog.setBlogstatus(1);
        blogService.updateBlog(blog);
        return Msg.success();
    }

    //置顶博客
    @RequestMapping(value = "/setTopBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg setTopBlog(@RequestParam String id) {
        Blog blog = new Blog();
        blog.setId(id);
        //设置为置顶
        blog.setTop(1);
        blogService.updateBlog(blog);
        return Msg.success();
    }

    //取消置顶
    @RequestMapping(value = "/cancelSetTopBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg cancelSetTopBlog(@RequestParam String id) {
        Blog blog = new Blog();
        blog.setId(id);
        //设置为置顶
        blog.setTop(0);
        blogService.updateBlog(blog);
        return Msg.success();
    }


    //获取指定博客
    @RequestMapping(value = "/getBlogById/{blogId}", method = RequestMethod.GET)
    @ResponseBody
    public Msg getBlogById(@PathVariable String blogId) {
        return Msg.success().add("blog", blogService.getBlogById(blogId));
    }


    //删除博客
    @RequestMapping(value = "/delBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg delBlog(@RequestParam String id) {
        blogService.delBlog(id);
        return Msg.success();
    }

    //跳转到修改博客页面
    @RequestMapping(value = "/editBlog/{blogId}", method = RequestMethod.GET)
    public String goToEditBlog(@PathVariable String blogId, ModelMap modelMap, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        Blog blog = blogService.getBlogById(blogId);
        if (blog == null) {
            return "redirect:/error";
        }
        //判断该用户是否为作者
        if (!blog.getUserid().equals(user.getId())) {
            return "redirect:/error";
        }
        modelMap.put("blog", blog);
        return "blog-update";
    }

    //博客修改提交
    @RequestMapping(value = "/updateBlog", method = RequestMethod.POST)
    @ResponseBody
    public Msg updateBlog(Blog blog) {
        blogService.updateBlog(blog);
        return Msg.success().add("blogId",blog.getId());
    }

    //查询用户所有博客，排除已经删除掉的博客
    @RequestMapping(value = "/getBlogsByUserId", method = RequestMethod.POST)
    @ResponseBody
    public Msg getUserAllBlog(@RequestParam String userId, @RequestParam Integer pn) {
        //开始分页
        PageHelper.startPage(pn, 10);
        List<Blog> blogs = blogService.getUserAllBlog(userId);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs, 5);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //查询用户垃圾箱
    @RequestMapping(value = "/getBlogsByUserId_trashcan", method = RequestMethod.POST)
    @ResponseBody
    public Msg getUserAllBlogWithTrashcan(@RequestParam String userId, @RequestParam Integer pn) {
        //开始分页
        PageHelper.startPage(pn, 10);
        List<Blog> blogs = blogService.getUserAllBlogWithTrashcan(userId);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs, 5);
        return Msg.success().add("pageInfo", pageInfo);
    }


    //查询指定类别下的所有博客
    @RequestMapping(value = "/getBlogsByTypeId", method = RequestMethod.POST)
    @ResponseBody
    public Msg getUserBlogByType(@RequestParam String typeId, @RequestParam Integer pn) {
        //开始分页
        PageHelper.startPage(pn, 10);
        List<Blog> blogs = blogService.getUserBlogByType(typeId);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs, 5);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //搜索指定用户的博客
    @RequestMapping(value = "/getBlogsByUserAndSearch", method = RequestMethod.GET)
    @ResponseBody
    public Msg getBlogsByUserAndSearch(@RequestParam String userId, @RequestParam String keyword, @RequestParam Integer pn) {
        //开始分页
        PageHelper.startPage(pn, 10);
        List<Blog> blogs = blogService.getUserBlogBySearch(userId, keyword);
        PageInfo<Blog> pageInfo = new PageInfo<>(blogs, 5);
        return Msg.success().add("pageInfo", pageInfo);
    }

    //blog-trashcan
    @RequestMapping(value = "/blog-trashcan", method = RequestMethod.GET)
    public String goToBlogTrashcan() {
        return "blog-trashcan";
    }

    //blog-byType
    @RequestMapping(value = "/blog-byType", method = RequestMethod.GET)
    public String goToByType() {
        return "blog-byType";
    }

    //blog-search
    @RequestMapping(value = "/blog-search", method = RequestMethod.GET)
    public String goToBlogSearch() {
        return "blog-search";
    }
}
